package com.visitorspecials.tankbattle.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Date;

public class TankBattleServer
{
	private ArrayList<Actor> actors;
	private TankBattleServer svr;		// Because Oracle/Sun is stupid.
	
	public ArrayList<Actor> getActors()
	{
		return this.actors;
	}

	private boolean isRunning = false;

	public TankBattleServer() throws IOException
	{
		this.svr = this;
		this.actors = new ArrayList<Actor>();
		Init();
	}

	private void Init() throws IOException
	{
		final ServerSocket server = new ServerSocket();
		server.bind(new InetSocketAddress(12345));

		ServerUpdateThread();
		
		new Thread(new Runnable() {

			@Override
			public void run()
			{
				do
				{
					Socket s;
					try
					{
						s = server.accept();
						
						Player p = new Player(svr, s);
						p.equals(null);
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} while (true);
			}
		}).start();
	}
	

	private static final int RUN_DELAY = 20;
	private void ServerUpdateThread()
	{
		new Thread(new Runnable() {

			@Override
			public void run()
			{
				while (true)
				{
					try
					{
						Thread.sleep(RUN_DELAY);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}

					Update();
				}
			}
		}).start();
	}

	private Date lastGameTime = new Date();
	
	public void Update()
	{
		Date gameTime = new Date();
		
		float elapsed = (gameTime.getTime() - lastGameTime.getTime()) / 1000.0f;
		
		lastGameTime = gameTime;
		
		
		for (Actor a : actors)
			// Update the actors to let them do their thing
			a.update(elapsed);

		// Now check for collisions
		for (int i = 0; i < actors.size(); i++)
		{
			for (int j = i + 1; j < actors.size(); j++)
			{
				if (actors.get(i).isColidingWith(actors.get(j)))
				{
					if (actors.get(i) instanceof Tank
							&& actors.get(j) instanceof Bullet)
					{
						Tank tank = (Tank) actors.get(i);
						Bullet bullet = (Bullet) actors.get(j);
						tank.wasShotBy(bullet);
						bullet.destroy();

					}
					else if (actors.get(j) instanceof Tank
							&& actors.get(i) instanceof Bullet)
					{
						Tank tank = (Tank) actors.get(j);
						Bullet bullet = (Bullet) actors.get(i);
						tank.wasShotBy(bullet);
						bullet.destroy();
					}
					if (actors.get(i) instanceof Bullet
							|| actors.get(i) instanceof Obstacle)
					{
						actors.remove(i);
					}
					else if (actors.get(j) instanceof Bullet
							|| actors.get(j) instanceof Obstacle)
					{
						actors.remove(j);
					}
				}
			}
		}
	}
}